package ar.uba.fi.RSACryptoFiuba.model.keygeneration;

import ar.uba.fi.RSACryptoFiuba.model.InvalidValueException;
import ar.uba.fi.RSACryptoFiuba.model.RSACalculator;
import ar.uba.fi.RSACryptoFiuba.model.RSAMessage;
import ar.uba.fi.RSACryptoFiuba.model.RSAStep;

public class CalculateDStep extends RSAStep {
	
	@Override
	public void execute(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message; 
		Integer phi = Integer.valueOf(keyGenerationMessage.getPhi());
		Integer d = RSACalculator.getCoprime(phi);
		keyGenerationMessage.setD(d.toString());
	}
	
	@Override
	public void undo(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		keyGenerationMessage.setD("");
	}

	@Override
	public void test(RSAMessage message) {
		String element = message.getElementToEvaluate();
		verifyNumericalValue(element);
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message; 
		Integer phi = Integer.valueOf(keyGenerationMessage.getPhi());
		Integer d = Integer.valueOf(element);
		boolean isValid = RSACalculator.areCoprime(phi, d);
		if(!isValid){
			throw new InvalidValueException("El número d debe ser relativamente primo (coprimo) de phi.");
		}
		keyGenerationMessage.setD(element);
	}

}
